<template>
  <div class="production-list">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="工单号">
        <el-input v-model="filters.orderNo" placeholder="请输入工单号" clearable />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model="filters.customer" placeholder="请输入客户名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filters.status" placeholder="请选择状态" clearable>
          <el-option label="全部" value="" />
          <el-option label="新建" value="新建" />
          <el-option label="进行中" value="进行中" />
          <el-option label="已完成" value="已完成" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="showAddDialog = true">新增</el-button>
      <el-button>导出</el-button>
      <el-button>更多</el-button>
    </div>

    <!-- 工单表格 -->
    <el-table :data="pagedData" border style="width: 100%; margin-top: 10px;">
      <el-table-column prop="index" label="序号" width="60" align="center" />
      <el-table-column prop="code" label="编码" width="150" align="center" />
      <el-table-column prop="source" label="来源" width="80" align="center" />
      <el-table-column prop="customer" label="客户" width="120" align="center" />
      <el-table-column prop="product" label="产品名称/规格" min-width="180" align="center" />
      <el-table-column prop="type" label="类型" width="100" align="center" />
      <el-table-column prop="status" label="状态" width="80" align="center" />
      <el-table-column prop="progress" label="工序进度" width="120" align="center" />
      <el-table-column prop="qty" label="数量" width="80" align="center" />
      <el-table-column prop="finishedQty" label="已完成数" width="100" align="center" />
      <el-table-column prop="rate" label="进度" width="80" align="center" />
      <el-table-column prop="planDate" label="计划结束时间" width="120" align="center"
        :formatter="row => formatDate(row.planDate)" />
      <el-table-column prop="startDate" label="达成开始时间" width="120" align="center"
        :formatter="row => formatDate(row.startDate)" />
      <el-table-column prop="endDate" label="达成结束时间" width="120" align="center"
        :formatter="row => formatDate(row.endDate)" />
      <el-table-column prop="putInQty" label="投入数量" width="100" align="center" />
      <el-table-column prop="goodQty" label="良品数量" width="100" align="center" />
      <el-table-column prop="badQty" label="不良数量" width="100" align="center" />
      <el-table-column prop="sender" label="发货" width="80" align="center" />
      <el-table-column prop="sendNo" label="发货号" width="120" align="center" />
      <el-table-column prop="remark" label="备注" min-width="100" align="center" />
      <el-table-column prop="creator" label="创建人" width="80" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="160" align="center"
        :formatter="row => formatDate(row.createTime)" />
      <el-table-column prop="updateTime" label="更新时间" width="160" align="center"
        :formatter="row => formatDate(row.updateTime)" />
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button size="small" type="text" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="small" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="text" danger @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 16px; text-align: right;"
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />

    <!-- 新增弹窗 -->
    <el-dialog title="新增工单" v-model="showAddDialog" width="600px">
      <el-form :model="addForm" label-width="110px" :rules="addRules" ref="addFormRef">
        <el-form-item label="编码" prop="code">
          <el-input v-model="addForm.code" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="类型" prop="type" required>
          <el-select v-model="addForm.type" placeholder="请选择类型">
            <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="customer" required>
          <el-select v-model="addForm.customer" placeholder="请选择客户">
            <el-option v-for="item in customerOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品主数据" prop="product" required>
          <el-select v-model="addForm.product" placeholder="请选择产品主数据">
            <el-option v-for="item in productOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺路线" prop="route" required>
          <el-select v-model="addForm.route" placeholder="请选择工艺路线">
            <el-option v-for="item in routeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="产线" prop="line" required>
          <el-select v-model="addForm.line" placeholder="请选择产线">
            <el-option v-for="item in lineOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划起止日期" prop="dateRange" required>
          <el-date-picker v-model="addForm.dateRange" type="daterange" range-separator="->" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="数量" prop="qty" required>
          <el-input v-model.number="addForm.qty" placeholder="请输入数量" type="number" min="1" />
        </el-form-item>
        <el-form-item label="是否允许跳工序" prop="allowSkip">
          <el-radio-group v-model="addForm.allowSkip">
            <el-radio :label="true">允许</el-radio>
            <el-radio :label="false">不允许</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="附件" prop="file">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleFileChange"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="编辑工单" v-model="showEditDialog" width="600px">
      <el-form :model="editForm" label-width="110px" :rules="addRules" ref="editFormRef">
        <el-form-item label="编码" prop="code">
          <el-input v-model="editForm.code" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="类型" prop="type" required>
          <el-select v-model="editForm.type" placeholder="请选择类型">
            <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="customer" required>
          <el-select v-model="editForm.customer" placeholder="请选择客户">
            <el-option v-for="item in customerOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品主数据" prop="product" required>
          <el-select v-model="editForm.product" placeholder="请选择产品主数据">
            <el-option v-for="item in productOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺路线" prop="route" required>
          <el-select v-model="editForm.route" placeholder="请选择工艺路线">
            <el-option v-for="item in routeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="产线" prop="line" required>
          <el-select v-model="editForm.line" placeholder="请选择产线">
            <el-option v-for="item in lineOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划起止日期" prop="dateRange" required>
          <el-date-picker v-model="editForm.dateRange" type="daterange" range-separator="->" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="数量" prop="qty" required>
          <el-input v-model.number="editForm.qty" placeholder="请输入数量" type="number" min="1" />
        </el-form-item>
        <el-form-item label="是否允许跳工序" prop="allowSkip">
          <el-radio-group v-model="editForm.allowSkip">
            <el-radio :label="true">允许</el-radio>
            <el-radio :label="false">不允许</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="附件" prop="file">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleEditFileChange"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="删除确认" v-model="showDeleteDialog" width="350px">
      <span>确定要删除该工单吗？</span>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const filters = reactive({
  orderNo: '',
  customer: '',
  status: ''
})

const tableData = ref<Array<{
  index: number,
  code: string,
  source: string,
  customer: string,
  product: string,
  type: string,
  status: string,
  progress: string,
  qty: number,
  finishedQty: number,
  rate: string,
  planDate: string,
  startDate: string,
  endDate: string,
  putInQty: number,
  goodQty: number,
  badQty: number,
  sender: string,
  sendNo: string,
  remark: string,
  creator: string,
  createTime: string,
  updateTime: string,
  allowSkip: boolean,
  file: any[],
  route: string,
  line: string
}>>([
  {
    index: 1,
    code: 'MO2023051610001',
    source: '平台',
    customer: '客户A',
    product: '685 3#P10-01 03 01 P16',
    type: '常规',
    status: '新建',
    progress: '0%',
    qty: 1,
    finishedQty: 0,
    rate: '0%',
    planDate: '2025-07-28',
    startDate: '2025-07-09',
    endDate: '2025-08-10',
    putInQty: 0,
    goodQty: 0,
    badQty: 0,
    sender: '张三',
    sendNo: 'MO2023051611001',
    remark: '备注',
    creator: 'testAAA',
    createTime: '2025-06-16 09:44:11',
    updateTime: '2025-06-17 19:54:22',
    allowSkip: false,
    file: [] as any[],
    route: '路线1',
    line: '产线1'
  },
  // ...可继续补充mock数据
])

const total = computed(() => tableData.value.length)
const pageSize = ref(10)
const currentPage = ref(1)

const showAddDialog = ref(false)
const showEditDialog = ref(false)
const showDeleteDialog = ref(false)
const addFormRef = ref()
const editFormRef = ref()
const typeOptions = ['类型A', '类型B', '类型C']
const customerOptions = ['客户A', '客户B', '客户C']
const productOptions = ['产品1', '产品2', '产品3']
const routeOptions = ['路线1', '路线2', '路线3']
const lineOptions = ['产线1', '产线2', '产线3']

interface AddFormType {
  code: string;
  type: string;
  customer: string;
  product: string;
  route: string;
  line: string;
  dateRange: [Date | null, Date | null] | [];
  qty: number | null;
  allowSkip: boolean;
  file: any[];
  remark: string;
}

const addForm = reactive<AddFormType>({
  code: '',
  type: '',
  customer: '',
  product: '',
  route: '',
  line: '',
  dateRange: [],
  qty: 0,
  allowSkip: false,
  file: [] as any[],
  remark: ''
})

const addRules = {
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
  product: [{ required: true, message: '请选择产品主数据', trigger: 'change' }],
  route: [{ required: true, message: '请选择工艺路线', trigger: 'change' }],
  line: [{ required: true, message: '请选择产线', trigger: 'change' }],
  dateRange: [{ required: true, message: '请选择计划起止日期', trigger: 'change' }],
  qty: [{ required: true, message: '请输入数量', trigger: 'blur' }]
}

const editForm = reactive({
  code: '',
  type: '',
  customer: '',
  product: '',
  route: '',
  line: '',
  dateRange: [],
  qty: 0,
  allowSkip: false,
  file: [] as any[],
  remark: '',
  _index: -1
})
const deleteIndex = ref(-1)

// 查询（筛选）
const filteredData = computed(() => {
  return tableData.value.filter(item => {
    const matchOrderNo = !filters.orderNo || item.code.includes(filters.orderNo)
    const matchCustomer = !filters.customer || item.customer.includes(filters.customer)
    const matchStatus = !filters.status || item.status === filters.status
    return matchOrderNo && matchCustomer && matchStatus
  })
})

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

function handleSearch() {
  // TODO: 实现筛选逻辑
}
function handleReset() {
  filters.orderNo = ''
  filters.customer = ''
  filters.status = ''
}
function handlePageChange(page: number) {
  currentPage.value = page
}
function handleFileChange(file: any) {
  addForm.file = [file]
}
function submitAddForm() {
  addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const newIndex = tableData.value.length + 1
      tableData.value.push({
        index: newIndex,
        code: 'MO' + Date.now(),
        source: '平台',
        customer: addForm.customer,
        product: addForm.product,
        type: addForm.type,
        status: '新建',
        progress: '0%',
        qty: addForm.qty || 0, // 添加默认值0，避免null值
        finishedQty: 0,
        rate: '0%',
        planDate: addForm.dateRange[1] ? String(addForm.dateRange[1]) : '',
        startDate: addForm.dateRange[0] ? String(addForm.dateRange[0]) : '',
        endDate: addForm.dateRange[1] ? String(addForm.dateRange[1]) : '',
        putInQty: 0,
        goodQty: 0,
        badQty: 0,
        sender: '',
        sendNo: '',
        remark: addForm.remark,
        creator: 'testAAA',
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString(),
        allowSkip: addForm.allowSkip,
        file: addForm.file,
        route: addForm.route,
        line: addForm.line
      })
      showAddDialog.value = false
      Object.assign(addForm, {
        code: '', type: '', customer: '', product: '', route: '', line: '', dateRange: [], qty: 0, allowSkip: false, file: [], remark: ''
      })
      ElMessage.success('新增成功')
    }
  })
}
function handleEdit(row: any) {
  editForm.code = row.code
  editForm.type = row.type
  editForm.customer = row.customer
  editForm.product = row.product
  editForm.route = row.route || ''
  editForm.line = row.line || ''
  editForm.dateRange = row.startDate && row.endDate ? [row.startDate, row.endDate] : []
  editForm.qty = row.qty
  editForm.allowSkip = row.allowSkip ?? false
  editForm.file = row.file || []
  editForm.remark = row.remark
  editForm._index = row.index - 1
  showEditDialog.value = true
}
function handleEditFileChange(file: any) {
  editForm.file = [file]
}
function submitEditForm() {
  editFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const idx = editForm._index
      if (idx >= 0 && idx < tableData.value.length) {
        tableData.value[idx].code = editForm.code
        tableData.value[idx].type = editForm.type
        tableData.value[idx].customer = editForm.customer
        tableData.value[idx].product = editForm.product
        tableData.value[idx].route = editForm.route
        tableData.value[idx].line = editForm.line
        tableData.value[idx].startDate = editForm.dateRange[0]
        tableData.value[idx].endDate = editForm.dateRange[1]
        tableData.value[idx].qty = editForm.qty
        tableData.value[idx].allowSkip = editForm.allowSkip
        tableData.value[idx].file = editForm.file
        tableData.value[idx].remark = editForm.remark
        tableData.value[idx].updateTime = new Date().toLocaleString()
      }
      showEditDialog.value = false
      ElMessage.success('编辑成功')
    }
  })
}
function handleDelete(row: any) {
  deleteIndex.value = row.index - 1
  showDeleteDialog.value = true
}
function confirmDelete() {
  if (deleteIndex.value >= 0) {
    tableData.value.splice(deleteIndex.value, 1)
    // 重新排序index
    tableData.value.forEach((item, idx) => item.index = idx + 1)
  }
  showDeleteDialog.value = false
}
function handleDetail(row: any) {
  // 可实现详情弹窗或跳转
  alert('工单详情：' + JSON.stringify(row, null, 2))
}
function formatDate(val: string) {
  if (!val) return ''
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.production-list {
  padding: 24px;
  background: #fff;
}
.filter-form {
  margin-bottom: 16px;
}
.toolbar {
  margin-bottom: 10px;
}
</style>
